<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="付款单号" prop="paymentOrder">
        <el-input
          v-model="queryParams.paymentOrder"
          placeholder="请输入付款单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="paymentStatus">
        <el-select
          v-model="queryParams.paymentStatus"
          placeholder="请选择付款单状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.payment_slips_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleApproved"
          v-hasPermi="['finance:PaymentSlips:paymentApplicant']"
          >核准</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          :disabled="multiple"
          @click="handleOverrule"
          v-hasPermi="['finance:PaymentSlips:paymentApplicant']"
          >驳回</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-finished"
          size="mini"
          :disabled="multiple"
          @click="handlePosting"
          v-hasPermi="['finance:PaymentSlips:posting']"
          >过账</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['finance:PaymentSlips:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="PaymentSlipsList"
      @selection-change="handleSelectionChange"
      ref="myTable"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="付款单号" align="center" prop="paymentOrder" />
      <el-table-column label="付款单类型" align="center" prop="paymentType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.payment_slips_type"
            :value="scope.row.paymentType"
          />
        </template>
      </el-table-column>
      <el-table-column label="供应商编号" align="center" prop="vendorNumber" />
      <el-table-column label="供应商名称" align="center" prop="name" />
      <el-table-column
        label="银行卡号"
        align="center"
        prop="bankCards"
      ></el-table-column>
      <el-table-column label="采购订单号" align="center" prop="ordersNumber" />
      <el-table-column label="预付金额" align="center" prop="requestAmount" />
      <el-table-column label="货币" align="center" prop="monetaryName" />
      <el-table-column label="制单" align="center">
        <template slot-scope="scope">
          {{ scope.row.applicant }}<br />{{
            parseTime(scope.row.applicationDate, "{y}-{m}-{d}")
          }}
        </template>
      </el-table-column>
      <el-table-column label="核准" align="center">
        <template slot-scope="scope">
          {{ scope.row.paymentApplicant }}<br />{{
            parseTime(scope.row.paymentApplicationDate, "{y}-{m}-{d}")
          }}
        </template>
      </el-table-column>
      <el-table-column label="过账" align="center">
        <template slot-scope="scope">
          {{ scope.row.postingApplicant }}<br />{{
            parseTime(scope.row.postingApplicationDate, "{y}-{m}-{d}")
          }}
        </template>
      </el-table-column>
      <el-table-column label="付款单状态" align="center" prop="paymentStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.payment_slips_status"
            :value="scope.row.paymentStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="[
              'finance:PaymentSlips:paymentApplicant',
              'finance:PaymentSlips:paymentApplicant',
              'finance:PaymentSlips:posting',
              'finance:PaymentSlips:query',
            ]"
          >
            <el-button size="mini" type="text" icon="el-icon-d-arrow-right"
              >更多</el-button
            >
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="handleApproved"
                icon="el-icon-check"
                v-hasPermi="['finance:PaymentSlips:paymentApplicant']"
                v-if="scope.row.paymentStatus == 0"
                >核准</el-dropdown-item
              >
              <el-dropdown-item
                command="handleOverrule"
                icon="el-icon-close"
                v-hasPermi="['finance:PaymentSlips:paymentApplicant']"
                v-if="
                  scope.row.paymentStatus == 0 || scope.row.paymentStatus == 1
                "
                >驳回</el-dropdown-item
              >
              <el-dropdown-item
                command="handlePosting"
                icon="el-icon-finished"
                v-hasPermi="['finance:PaymentSlips:posting']"
                v-if="scope.row.paymentStatus == 1"
                >过账</el-dropdown-item
              >
              <el-dropdown-item
                command="handleDetail"
                icon="el-icon-document"
                v-hasPermi="['finance:PaymentSlips:query']"
                v-if="scope.row.paymentStatus == 2"
                >查看</el-dropdown-item
              >

              <el-dropdown-item
                command="handleUpload"
                icon="el-icon-picture-outline"
                v-hasPermi="['finance:PaymentSlips:upload']"
                v-if="
                  (scope.row.waterBillImg == '' ||
                    scope.row.waterBillImg == null) &&
                  scope.row.paymentStatus == 2
                "
                >上传水单</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 付款单详情页 -->
    <el-dialog
      :title="titleQuery"
      :visible.sync="openQuery"
      width="1000px"
      append-to-body
    >
      <el-form ref="form" :model="formQuery" :rules="rules" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="付款单号:" prop="paymentOrder">
              {{ formQuery.paymentOrder }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="付款单类型:" prop="paymentType">
              {{ paymentTypeText }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商:" prop="name">
              {{ formQuery.name }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购订单号:" prop="planNumber">
              {{ formQuery.planNumber }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预付款金额:" prop="requestAmount">
              {{ formQuery.requestAmount }} <span>¥</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货币:" prop="monetaryName">
              {{ formQuery.monetaryName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="付款账号:" prop="bankCards">
              {{ formQuery.bankCards }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际付款日期:" prop="postingApplicationDate">
              {{ parseTime(formQuery.postingApplicationDate, "{y}-{m}-{d}") }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="过账人:" prop="postingApplicant">
              {{ formQuery.postingApplicant }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="过账日期:" prop="postingApplicationDate">
              {{ parseTime(formQuery.postingApplicationDate, "{y}-{m}-{d}") }}
              {{
                parseTime(formQuery.postingApplicationDate, "{hh}:{mm}:{ss}")
              }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单人:" prop="applicant">
              {{ formQuery.applicant }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单日期:" prop="applicationDate">
              {{ parseTime(formQuery.applicationDate, "{y}-{m}-{d}") }}
              {{ parseTime(formQuery.applicationDate, "{hh}:{mm}:{ss}") }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="核准人:" prop="paymentApplicant">
              {{ formQuery.paymentApplicant }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="核准日期:" prop="paymentApplicationDate">
              {{ parseTime(formQuery.paymentApplicationDate, "{y}-{m}-{d}") }}
              {{
                parseTime(formQuery.paymentApplicationDate, "{hh}:{mm}:{ss}")
              }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="requestRemark">
              <el-input
                v-model="formQuery.requestRemark"
                placeholder="请选择"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="水单:"
              prop="waterBillImg"
              v-if="formQuery.waterBillImg"
            >
              <el-image :src="formQuery.waterBillImg" style="width: 30%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 上传水单 -->
    <el-dialog
      :title="titleUpload"
      :visible.sync="openUpload"
      width="600px"
      append-to-body
      @close="cancel"
    >
      <el-form ref="form" :model="formUpload" :rules="rules" label-width="80px">
        <el-upload
          class="upload-demo"
          ref="upload"
          :limit="1"
          accept=".jpg, .png"
          :action="upload.url"
          :headers="upload.headers"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :file-list="upload.fileList"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleUpdate">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPaymentSlips,
  getPaymentSlips,
  delPaymentSlips,
  updatePaymentSlips,
  getUpdatePaymentApplicant,
  getSelectPaymentApplicantByPaymentId,
  getUpdatePostingApplicant,
} from "@/api/finance/PaymentSlips";
import { getRequestAdvanceByRequestId } from "@/api/orders/ProcuredOrders";
import { getUpdateAdvanceApplicant } from "@/api/finance/advance";
import { getToken } from "@/utils/auth";
export default {
  name: "PaymentSlips",
  dicts: ["payment_slips_type", "payment_slips_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 付款单表格数据
      PaymentSlipsList: [],
      // 弹出层标题
      title: "",
      titleQuery: "",
      titleUpload: "",
      // 是否显示弹出层
      open: false,
      openQuery: false,
      openUpload: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paymentOrder: null,
        paymentStatus: null,
      },
      // 表单参数
      form: {},
      formQuery: {},
      formUpload: {},
      // 表单校验
      rules: {},

      // 上传参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: [],
      },
    };
  },
  created() {
    this.getList();
  },
  computed: {
    paymentTypeText() {
      const paymentTypes = {
        0: "采购应付款",
        1: "采购预付款",
      };
      return paymentTypes[this.formQuery.paymentType] || "";
    },
  },
  methods: {
    /** 查询付款单列表 */
    getList() {
      this.loading = true;
      listPaymentSlips(this.queryParams).then((response) => {
        this.PaymentSlipsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        paymentId: null,
        paymentOrder: null,
        paymentType: null,
        advanceId: null,
        paymentApplicant: null,
        paymentApplicationDate: null,
        postingApplicant: null,
        postingApplicationDate: null,
        paymentStatus: null,
        deleteStatus: null,
        createTime: null,
        updateTime: null,
      };
      this.formUpload = {
        paymentId: null,
        waterBillImg: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.paymentId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查看按钮操作 */
    handleDetail(row) {
      this.reset();
      const paymentId = row.paymentId || this.ids;
      getPaymentSlips(paymentId).then((response) => {
        this.formQuery = response.data;
        this.openQuery = true;
        this.titleQuery = "付款单查看";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.openQuery = false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paymentIds = row.paymentId || this.ids;
      this.$modal
        .confirm('是否确认删除付款单编号为"' + paymentIds + '"的数据项？')
        .then(function () {
          return delPaymentSlips(paymentIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "finance/PaymentSlips/export",
        {
          ...this.queryParams,
        },
        `PaymentSlips_${new Date().getTime()}.xlsx`
      );
    },
    /** 核准按钮 */
    handleApproved(row) {
      const paymentIds = row.paymentId || this.ids;
      this.$modal
        .confirm("您确认所选数据批量核准吗？")
        .then(() => {
          return getSelectPaymentApplicantByPaymentId(paymentIds);
        })
        .then((response) => {
          var index = 0;
          for (let i = 0; i < response.data.length; i++) {
            if (response.data[i].paymentApplicant != null) {
              this.$modal.msgWarning("核准失败，所勾选项包含已核准！");
              this.$refs.myTable.clearSelection();
              index++;
              return Promise.reject(); // 返回一个拒绝的 Promise，使后续的代码不会执行
            }
          }
          if (index == 0) {
            return getUpdatePaymentApplicant(paymentIds, true);
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("核准成功！");
        })
        .catch(() => {});
    },
    /** 驳回 */
    handleOverrule(row) {
      const paymentIds = row.paymentId || this.ids;
      this.$modal
        .confirm("您确定将所选记录驳回吗？")
        .then(() => {
          return getSelectPaymentApplicantByPaymentId(paymentIds);
        })
        .then((response) => {
          var index = 0;
          let requestIds = [];
          for (let i = 0; i < response.data.length; i++) {
            if (response.data[i].paymentStatus == 2) {
              this.$modal.msgWarning("驳回失败，所选数据中包含已过账数据！");
              this.$refs.myTable.clearSelection();
              index++;
              return Promise.reject(); // 返回一个拒绝的 Promise，使后续的代码不会执行
            } else {
              requestIds.push(response.data[i].requestId); // 将requestId添加到数组中
            }
          }
          if (index == 0) {
            getRequestAdvanceByRequestId(requestIds);
            getUpdateAdvanceApplicant(requestIds, false);
            return getUpdatePaymentApplicant(paymentIds, false);
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("驳回成功！");
        })
        .catch(() => {});
    },
    /** 过账 */
    handlePosting(row) {
      const paymentIds = row.paymentId || this.ids;
      this.$modal
        .confirm("您确定将所选记录过账吗？")
        .then(() => {
          return getSelectPaymentApplicantByPaymentId(paymentIds);
        })
        .then((response) => {
          var index = 0;
          for (let i = 0; i < response.data.length; i++) {
            if (response.data[i].paymentStatus == 0) {
              this.$modal.msgError("过账失败，所选数据中还没有核准！");
              this.$refs.myTable.clearSelection();
              index++;
              return Promise.reject(); // 返回一个拒绝的 Promise，使后续的代码不会执行
            }
            if (response.data[i].paymentStatus == 2) {
              this.$modal.msgWarning("过账失败，该选数据中已经存在过账！");
              this.$refs.myTable.clearSelection();
              index++;
              return Promise.reject(); // 返回一个拒绝的 Promise，使后续的代码不会执行
            }
          }
          if (index == 0) {
            return getUpdatePostingApplicant(paymentIds);
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("过账成功！");
        })
        .catch(() => {});
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleApproved":
          this.handleApproved(row);
          break;
        case "handleOverrule":
          this.handleOverrule(row);
          break;
        case "handlePosting":
          this.handlePosting(row);
          break;
        case "handleDetail":
          this.handleDetail(row);
          break;
        case "handleUpload":
          this.handleUpload(row);
          break;
        default:
          break;
      }
    },
    /** 上传水单 */
    handleUpload(row) {
      const paymentIds = row.paymentId || this.ids;
      this.titleUpload = "上传水单";
      this.openUpload = true;
      this.formUpload.paymentId = paymentIds;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.formUpload.waterBillImg = response.url;
    },
    //上传水单确认按钮
    handleUpdate() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.formUpload.paymentId != null) {
            updatePaymentSlips(this.formUpload).then(() => {
              this.$modal.msgSuccess("上传水单成功！");
              this.openUpload = false;
              this.getList();
            });
          }
        }
      });
    },
    //上传水单取消按钮
    cancel() {
      this.openUpload = false;
      this.$refs.upload.clearFiles();
      this.reset();
    },
  },
};
</script>
